import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Layout } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { httpClient } from '../../common/httpClient';
import { LoginRequest, LoginResponse } from '../../types/login';

const { Title } = Typography;
const { Header, Content } = Layout;

const LoginPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const handleLogin = async (values: LoginRequest) => {
    try {
      setLoading(true);
      
      // 调用登录接口
      const response = await httpClient.post<LoginResponse>(
        '/admin/users/login',
        values,
        {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        }
      );

      if (response.data.code === 200 && response.data.data) {
        // 保存token到localStorage
        localStorage.setItem('token', response.data.data.token);
        localStorage.setItem('userId', response.data.data.userId.toString());
        localStorage.setItem('userInfo', JSON.stringify(response.data.data));
        
        // message.success('登录成功');
        
        // 登录成功后跳转到项目管理project页面
         window.location.href = '/project';
        // navigate('/project');
      } else {
        message.error(response.data.msg || '登录失败');
      }
    } catch (error: any) {
      message.error(error.msg || '登录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout className="layout" style={{ minHeight: '100vh' }}>
      <Header style={{ backgroundColor: '#fff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }}>
        <div style={{ textAlign: 'center', padding: '10px 0' }}>
          <Title level={3} style={{ color: '#4a3c8c', margin: 0 }}>
            物联网设备管理系统
          </Title>
        </div>
      </Header>
      <Content style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '20px' }}>
        <Card 
          title="用户登录" 
          style={{ 
            width: 400, 
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            borderRadius: '8px',
            border: 'none'
          }}
          className="login-card"
        >
          <Form
            form={form}
            name="login"
            layout="vertical"
            onFinish={handleLogin}
            initialValues={{
              user_name: '',
              pass: '',
            }}
          >
            <Form.Item
              name="user_name"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
              ]}
            >
              <Input
                prefix={<UserOutlined className="site-form-item-icon" />}
                placeholder="请输入用户名"
                size="large"
              />
            </Form.Item>
            
            <Form.Item
              name="pass"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="请输入密码"
                size="large"
              />
            </Form.Item>
            
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
                loading={loading}
                size="large"
                style={{ width: '100%', backgroundColor: '#4a3c8c' }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Content>
    </Layout>
  );
};

export default LoginPage;